<!DOCTYPE html PUBLIC "-//W4C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title>Google Maps</title>
    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=ABQIAAAAzrOhydvk6aOjdI3StFhy1xT2yXp_ZAY8_ufC3CFXhHIE1NvwkxSGSrVHCQ1Vv7tR5qbMOUwg8Ehe0Q type="text/javascript"></script>
  </head>
  <body onunload="GUnload()">

    <!-- you can use tables or divs for the overall layout -->
    <table border=1>
      <tr>
        <td>
           <div id="map" style="width: 1200px; height: 600px"></div>
        </td>
	<td width = 200 valign="top" style="text-decoration: underline; color: #4444ff;">
           <div id="side_bar"></div>
        </td>
      </tr>
    </table>

    <noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b> 
      However, it seems JavaScript is either disabled or not supported by your browser. 
      To view Google Maps, enable JavaScript by changing your browser options, and then 
      try again.
    </noscript>


    <script type="text/javascript">
    //<![CDATA[

    if (GBrowserIsCompatible()) {
      var side_bar_html = "";
    
      // arrays to hold copies of the markers used by the side_bar
      // because the function closure trick doesnt work there
      var gmarkers = [];
      var newPathPoints = [];
      var newPath;
      var newXml;

      var xmlDoc;

      // A function to create the marker and set up the event window
      function createMarker(point,name) {
        var marker = new GMarker(point);
        GEvent.addListener(marker, "click", completePath);
        gmarkers.push(marker);
        return marker;
      }

      function completePath(latlng) {
        var xpath = "/dest-routes/dest-route/landmark[@lat='" + latlng.lat() + "' and @lng='" + latlng.lng() + "']"; 
        var nodes = xmlDoc.evaluate(xpath, xmlDoc, null, XPathResult.ANY_TYPE, null);
	var result = nodes.iterateNext();
	var newatt;

	newPath.insertVertex(newPath.getVertexCount(), latlng);

        newXml = xmlDoc.createElement("dest-routes");
	newatt = xmlDoc.createAttribute("dest-id");
	newatt.nodeValue = xmlDoc.documentElement.getAttribute("dest-id");
	newXml.setAttributeNode(newatt);
	newatt = xmlDoc.createAttribute("dest-time");
	newatt.nodeValue = xmlDoc.documentElement.getAttribute("dest-time");
	newXml.setAttributeNode(newatt);

	newXml.appendChild(xmlDoc.createElement("dest-route"));

	newXml.firstChild.appendChild(result.cloneNode(true));

        while (result && result.parentNode.lastChild != result) {

	  result = result.nextSibling;
	  while (result && result.nodeType != 1) {
	    result = result.nextSibling;
	  }

          if (result) {
	    latlng = new GLatLng(result.getAttribute('lat'), result.getAttribute('lng'));
	    newPath.insertVertex(newPath.getVertexCount(), latlng);
	    newXml.firstChild.appendChild(result.cloneNode(true));
	  }
	}

        //alert(newPath.getVertexCount());
	alert((new XMLSerializer()).serializeToString(newXml));
      }

      function addLandmark(overlay, latlng) {
        var icon = new GIcon(G_DEFAULT_ICON);
	icon.image = "http://labs.google.com/ridefinder/images/mm_20_blue.png";
        var marker = new GMarker(latlng, {icon: icon});
	newPathPoints.push(marker);
	map.addOverlay(marker);

	newPath.insertVertex(newPath.getVertexCount(), latlng);
      }

      function clearDest() {
        map.removeOverlay(newPath);

        newPath = new GPolyline([], "green");
	map.addOverlay(newPath);

	for (i = 0; i < newPathPoints.length; i++) {
	  map.removeOverlay(newPathPoints[i]);
	}

        newXml = "";
	newPathPoints = [];
      }

      function submitDest() {
	var landmark;
	var newatt;

	var destNode = newXml.firstChild;
	var mergeNode = destNode.firstChild;

	for (i = 0; i < newPathPoints.length; i++) {
	    landmark = xmlDoc.createElement("landmark");

            var lat = newPathPoints[i].getLatLng().lat();
	    var lng = newPathPoints[i].getLatLng().lng();

	    newatt = xmlDoc.createAttribute("lat");
	    newatt.nodeValue = lat;
	    landmark.setAttributeNode(newatt);

	    newatt = xmlDoc.createAttribute("lng");
	    newatt.nodeValue = lng;
	    landmark.setAttributeNode(newatt);

	    newatt = xmlDoc.createAttribute("landmark-id");
	    newatt.nodeValue = "";
	    landmark.setAttributeNode(newatt);

            destNode.insertBefore(landmark, mergeNode);
	}

	var xmlString = (new XMLSerializer()).serializeToString(newXml);
	alert(xmlString);
      }

      // create the map
      var map = new GMap2(document.getElementById("map"), {draggableCursor:'url(arrow_rl.cur),default'});
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());


      function markerPresent(point) {
          // better way to check ?
          for (var l = 0; l < gmarkers.length; l++) {
              if (gmarkers[l].getLatLng().equals(point)) {
                  return true;
              }
          }

          return false;
      }

      // Read the data from example.xml
      GDownloadUrl("dest_routes.xml", function(doc) {
        xmlDoc = GXml.parse(doc);
        var routes = xmlDoc.documentElement.getElementsByTagName("dest-route");

	var minlat = 0xffff, maxlat = -0xffff, minlng = 0xffff, maxlng = -0xffff;
          
        for (var i = 0; i < routes.length; i++) {
	  var landmarks = routes[i].getElementsByTagName("landmark");
	  var pts = [];
	  for (var j = 0; j < landmarks.length; j++) {
	    var lat = parseFloat(landmarks[j].getAttribute("lat"));
	    var lng = parseFloat(landmarks[j].getAttribute("lng"));

            if (lat < minlat) minlat = lat;
            if (lat > maxlat) maxlat = lat;
            if (lng < minlng) minlng = lng;
            if (lng > maxlng) maxlng = lng;

	    var point = new GLatLng(lat,lng);
	    pts[j] = point;

            if (!markerPresent(point)) {
	      var label = landmarks[i].getAttribute("landmark-name");
	      var marker = createMarker(point,label);
	      map.addOverlay(marker);
	    }
	  }

	  map.addOverlay(new GPolyline(pts));
        }

	map.setCenter(new GLatLng((maxlat + minlat) / 2, (maxlng + minlng) / 2), 13);

        GEvent.addListener(map, "click", addLandmark);

        newPath = new GPolyline([], "green");
	map.addOverlay(newPath);

        // put the assembled side_bar_html contents into the side_bar div
	side_bar_html = "<a href=javascript:clearDest()>Reset</a><br>";
	side_bar_html += "<a href=javascript:submitDest()>Submit route</a>";
        document.getElementById("side_bar").innerHTML = side_bar_html;
      });
    }

    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }

    // This Javascript is based on code provided by the
    // Community Church Javascript Team
    // http://www.bisphamchurch.org.uk/   
    // http://econym.org.uk/gmap/

    //]]>
    </script>
  </body>

</html>

